#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include "RingQueue.hpp"

using namespace std;

void * Productor(void* args)
{
    // sleep(3);
    ThreadData* td = static_cast<ThreadData*>(args);
    RingQueue<int> * rq = td->_rq;
    std::string name = td->_threadname;
    // RingQueue<int> * rq = static_cast<RingQueue<int>*>(args);
    while(true)
    {
        // 1、获取数据
        int data = rand() % 10 + 1;
        // 2、生产数据
        rq->Push(data);
        cout << "Prouductor data done, data is : " << data << ",who: " << name << endl;
        // sleep(1);
    }
    return nullptr;
}

void* Consumer(void* args)
{
    ThreadData* td = static_cast<ThreadData*>(args);
    RingQueue<int> * rq = td->_rq;
    std::string name = td->_threadname;
    // RingQueue<int> * rq = static_cast<RingQueue<int>*>(args);
    while(true)
    {
        sleep(1);
        // 1、消费数据
        int data = 0;
        rq->Pop(&data);
        cout << "Consumer get data , data is : " << data << ",who: " << name  << endl;
        // sleep(1);
        // 2、处理数据
    }
    return nullptr;
}

int main()
{
    srand(time(nullptr));
    RingQueue<int> *rq = new RingQueue<int>();

    pthread_t c[5], p[3];
    for(int i = 0; i < 3; ++i){
        ThreadData* td = new ThreadData();
        td->_rq = rq;
        td->_threadname = "Productor-" + std::to_string(i);

        pthread_create(p + i, nullptr, Productor, td);
    }

    for(int i = 0; i < 5; ++i)
    {
        ThreadData* td = new ThreadData();
        td->_rq = rq;
        td->_threadname = "Consumer-" + std::to_string(i);
        pthread_create(c + i, nullptr, Consumer, td);
    }

    for(int i = 0 ; i < 3; ++i)
    {
        pthread_join(p[i], nullptr);
    }
    
    for(int i = 0; i < 5; ++i)
    {
        pthread_join(c[i], nullptr);
    }

    return 0;
}